package cc.mxtt.mvc.controller;

import java.util.HashMap;
import java.util.Map;

import com.jfinal.aop.Before;
import com.jfinal.kit.JsonKit;

import cc.mxtt.common.core.BaseController;
import cc.mxtt.mvc.interceptor.MenuLogInterceptor;
import cc.mxtt.mvc.model.Menu;
import cc.mxtt.mvc.service.MenuService;
import cc.mxtt.mvc.service.impl.MenuServiceImpl;

public class MenuController extends BaseController{
	MenuService menuService = new MenuServiceImpl();
	
	public void index(){
		render("index.jsp");
	}
	
	public void list(){
		renderJson(JsonKit.toJson(menuService.getTreeGrid("0")));
	}
	
	public void tree(){
		String role_id = getPara(0);
		//顶级菜单的parent_id=0
		renderJson(JsonKit.toJson(menuService.getTree(role_id,"0")));
	}
	@Before(MenuLogInterceptor.class)
	public void add(){
		Menu menu = new Menu();
		menu.set("name", getPara("name"));
		menu.set("description", getPara("description"));
		menu.set("iconCls", getPara("iconCls"));
		menu.set("url", getPara("url"));
		menu.set("parent_id", getPara("parent_id"));
		menu.set("order_id", getPara("order_id"));
		Map<String, Boolean> result = new HashMap<String, Boolean>();
		if (menuService.create(menu)) {
			result.put("flag", true);		
		}else{
			result.put("flag", true);
		}
		renderJson(JsonKit.toJson(result));
	}
	@Before(MenuLogInterceptor.class)
	public void edit(){
		Menu menu = menuService.findById(getPara("id"));
		menu.set("name", getPara("name"));
		menu.set("description", getPara("description"));
		menu.set("iconCls", getPara("iconCls"));
		menu.set("url", getPara("url"));
		menu.set("parent_id", getPara("parent_id"));
		menu.set("order_id", getPara("order_id"));
		Map<String, Boolean> result = new HashMap<String, Boolean>();
		if (menuService.update(menu)){
			result.put("flag", true);		
		}else{
			result.put("flag", true);
		}
		renderJson(JsonKit.toJson(result));
	}
	@Before(MenuLogInterceptor.class)
	public void delete(){
		Map<String, Object> result = new HashMap<String, Object>();
		boolean flag = true;
		String Msg = "";
		if (menuService.existsMenu(getPara("id"))){
			flag = false;
			Msg = "该菜单下有子菜单，不能删除！";
		}else{
			menuService.deleteRoleMenuByMenuId(getPara("id"));
			if (menuService.delete(getPara("id"))){
				Msg = "删除成功！";
			}else{
				flag = false;
				Msg = "删除失败！";
			}
		}
		result.put("flag", flag);
		result.put("Msg", Msg);
		renderJson(JsonKit.toJson(result));
	}
	
	public void upparentid(){
		Menu menu = menuService.findById(getPara("menuid"));
		menu.set("parent_id", getPara("parentid"));
		Map<String, Boolean> result = new HashMap<String, Boolean>();
		if (menuService.update(menu)){
			result.put("flag", true);
		}else{
			result.put("flag", false);
		}
		renderJson(JsonKit.toJson(result));
	}
}
